local oo = require("SharedLibs.BaseLib")
local co = require("SharedLibs.CoroLib")

Debugger = require("SharedLibs.Debugger")
TimerMgr = require("SharedLibs.TimerMgr")
AsyncOp = require("SharedLibs.AsyncOp")

--- When guardFunc is true, operation will complete.
co.GuardOp = oo.Class();
local GuardOp = co.GuardOp;
GuardOp.name = "GuardOp";
oo.ClassExtends(GuardOp, AsyncOp);

function co.Guard(guardFunc)
	local op = oo.New(co.GuardOp, guardFunc);
	return co.yield(op);
end

function co.NewGuard(guardFunc)
	return oo.New(co.GuardOp, guardFunc);
end

function GuardOp.prototype:constructor(guardFunc)
	GuardOp._ss.prototype.constructor(self)
	
	self._state = co.AsyncOpState.Ready
	self._guardFunc = guardFunc;
	
	--- Implements ITickable
	self.isInQueue = false;
	self.isStopped = false;
end

function GuardOp.prototype:_onStart()
	if self._guardFunc() then 
		self:_doStop(true);
	else
		TimerMgr.Enqueue(self);
	end	
end

function GuardOp.prototype:_onStop()
	self.isStopped = true;
end

function GuardOp.prototype:_onReset()
	self.isStopped = false;
end

function GuardOp.prototype:Update()
	if self._state ~= co.AsyncOpState.Executing then return; end;

	if self._guardFunc() then 
		self:_doStop(true);
	end
end

return GuardOp;
